import util from '../../utils/util.js';
import commonAPI from '../../api/api'
const FN = require('../../utils/public');
var app = getApp();
Page({

  data: {
    priTmplIdArr: [], 
    integralNum: 0,
    src: '',
    maxScore: 0,
    scoreDetail: {},
    errorWordsObj: {},
    btns: '1',
    wordsArr: [],
    hasLogin: true,
    pointsConfig: {},// 積分配置
    autoplay: false,
    interval: 2000,
    duration: 500,
    teacherList: [],
    teacherInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromOpenedPage', {});
    eventChannel.emit('someEvent', {});
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      that.parsePronunciationResultUsingAIModel(data);// 根据AI模型解析纠音结果
    })
    wx.hideShareMenu(); // 禁止分享   
    this.adInit();
    this.getTeacherList();// 查询纠音老师集合
    this.getSubscribeMsg();
    const item = app.globalData.miniappInfo.pointsconfigList.find(item=>item.pointsConfigKey == 'manualErrorCorrection');
    this.setData({
      pointsConfig:item
    })
  },

  // 获取订阅消息
  getSubscribeMsg: function () {
    var that = this;
    commonAPI.getSubscribeMsg({ pageUrl: util.getCurrentPageUrl() }).then(res => {
      if (res.code == '200' && res.data.length > 0) {
        var arr = res.data[0].priTmplIdArr.split(",")
        that.setData({
          priTmplIdArr: arr
        })
      }
    })
  },

  adInit() {
    var that = this;
    var pageUrl = util.getCurrentPageUrl()
    var item = app.globalData.advertisement.find(obj => obj.advertisementPage === pageUrl)
    that.setData({
      adObj: item
    })
  },

  // 重新挑战
  returnBack: function () {
    wx.navigateBack();
  },

  // 人工纠音
  requestSubscribeMessage: function (e) {
    var that = this, teaid = 'teacherInfo.teaid', teaopenid = 'teacherInfo.teaopenid', type = e.currentTarget.dataset.type;
    if (!app.globalData.userInfo || !app.globalData.userInfo.signInfo || !app.globalData.userInfo.signInfo.nickName) {
      wx.showModal({
        title: '提示',
        content: '需要授权获取您的头像和昵称,才可以申请预约纠音',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../login/login'
            });
          }
        }
      });
      return;
    }

    that.setData({
      [teaopenid]: e.currentTarget.dataset.teaopenid,
      [teaid]: e.currentTarget.dataset.teaid
    })
    wx.requestSubscribeMessage({
      tmplIds: that.data.priTmplIdArr,
      success(res) { }
    })
    that.integralInsufficient(type);
  },

  // 积分不足function
  integralInsufficient: function (type) {// 01 免积分（专属纠音老师） 02 需要积分
    var that = this;
    if (type == '01') {
      that.applyCorrect(type);
    } else {
      if (that.data.integralNum < that.data.pointsConfig.pointsConfigValue) {
        that.navigateToPointsPageForVideo(that.data.integralNum);
      } else {
        that.applyCorrect(type);
      }
    }
  },

  // 跳转观看视频获取积分页面
navigateToPointsPageForVideo(integralNum){
  let promise = FN.Confirm(`当前积分：${integralNum?integralNum:0}，看视频可以获取积分，是否观看？`);
  promise.then(res => {
    wx.navigateTo({
      url: '../myIntegral/myIntegral'
    })
  }).catch(res => {

  });
},

  // 预约纠音
  applyCorrect: function (type) {
    var that = this;
    commonAPI.baPreCorrect({
      voiceResultId: that.data.scoreDetail.voiceResultId,
      nickName: app.globalData.userInfo.signInfo.nickName,
      teacherOpenId: that.data.teacherInfo.teaopenid,// 老师openid
      wdTeacherId: that.data.teacherInfo.teaid,
      "correctType": type,
      "settlementStatus": type == '01' ? "04" : "03",
      integraldetail:{
        integralId:app.globalData.userInfo.integralObj.integralId,
        integralDetailType:that.data.pointsConfig.pointsConfigType,
        integralDetailDesc:that.data.pointsConfig.pointsConfigName,
        integralDetailNum:that.data.pointsConfig.pointsConfigType === "1" ? that.data.pointsConfig.pointsConfigValue : -that.data.pointsConfig.pointsConfigValue
      }
    }).then(res => {
      var obj = res.data;
      if (obj.hasPrecorrect) {
        FN.Toast('本次跟读已预约过，不可重复预约');
      } else {
        if (obj.preCorrectStauts) {
          FN.Toast('预约成功');
        }else {
          FN.Toast('预约失败', 2, 4000);
        }
      }
    })
  },

  // 弹出框 
  one2oneCorrect: function (e) {
    wx.navigateTo({
      url: '../myIntegral/myIntegral',
      success: function (res) {

      },
      fail: function (res) {

      },
      complete: function (res) {

      }
    })

  },

  // 根据AI模型解析纠音结果
  parsePronunciationResultUsingAIModel(options) {
    var obj = options.vrObj;
    if (obj.voiceResultAIModel == '1') {
      this.dealOptionsData(obj);
    } else {
      this.dealOptionsData4SOE(obj);
    }
  },

  // 根据options参数做对应的业务处理
  dealOptionsData(obj) {
    var that = this;
    var errorWords = new Array();// 低于90分的单词
    const resultInfo = obj.voiceResultInfo;
    var { maxScore, errorWords } = util.getMaxPronAccuracy4free(resultInfo.result.words);// 计算最高分数及低于90分单词
    const errorWordObjTemp = {
      errorWordsArr: errorWords,
      voiceSystemId: obj.voiceSystemId
    };
    const { voiceResultInfo, oldWords } = that.formatWord(obj.voiceToen, obj)
    that.setData({
      scoreDetail: { ...obj, ...voiceResultInfo },
      maxScore: maxScore,// 句子最高得分
      wordsArr: voiceResultInfo.result.words,//obj.result.words,
      errorWordsObj: errorWordObjTemp// 低于90分的错误单词
    })
  },

  dealOptionsData4SOE(obj) {
    var that = this;
    var errorWords = new Array();// 低于90分的单词
    const resultInfo = obj.voiceResultInfo;
    var { maxScore, errorWords } = util.getMaxPronAccuracy4SOE(resultInfo.Words);// 计算最高分数及低于90分单词
    const errorWordObjTemp = {
      errorWordsArr: errorWords, 
      voiceSystemId: obj.voiceSystemId
    };
    const { voiceResultInfo, oldWords } = that.formatWord(obj.voiceToen, obj)
    that.setData({
      scoreDetail: { ...obj, ...voiceResultInfo },
      maxScore: maxScore,// 句子最高得分
      wordsArr: voiceResultInfo.Words,//obj.result.words,
      errorWordsObj: errorWordObjTemp// 低于90分的错误单词
    })
  },

  // 有跟读结果的，文本依旧保留原有文字，只是改变颜色而已
  formatWord(oldWordStr, item) {
    const oldWords = oldWordStr.trim().split(/\s+/);
    var voiceResultInfo = item.voiceResultInfo;
    if (item.voiceResultAIModel == '1') {
      voiceResultInfo.result.words.forEach((wordObj, index) => {
        if (oldWords[index]) {
          wordObj.word = oldWords[index];
        }
      });
    } else {
      voiceResultInfo.Words.forEach((wordObj, index) => {
        if (oldWords[index]) {
          wordObj.Word = oldWords[index];
        }
      });
    }
    return { voiceResultInfo, oldWords }
  },

  // 自己的录音
  myvoice: function (e) {
    var that = this;
    this.innerAudioContext.play();
    that.innerAudioContext.onPlay(function () {
      that.setData({
        btns: '2',
      })
    });

    // 音频暂停回调
    that.innerAudioContext.onStop(function () {
      that.setData({
        btns: '1',
      })
    });

    // 音频结束回调
    that.innerAudioContext.onEnded(function () {
      that.setData({
        btns: '1',
      })
    });
  },

  // 暂停
  stopMyvoice: function (e) {
    var that = this;
    that.innerAudioContext.pause();
    that.innerAudioContext.onPause(function () {
      that.setData({
        btns: '1'
      })
    })
  },

  // 错误单词
  errorWords: function (e) {
    var currWord = e.currentTarget.dataset.errorword,
      errorArr = new Array(),
      errorObj = {},
      that = this;
    var temArr = this.data.errorWordsObj.errorWordsArr;
    for (var i in temArr) {
      var obj = {};
      if (temArr[i] == currWord) {
        obj.errorWords = temArr[i];
        obj.voiceSystemId = that.data.errorWordsObj.voiceSystemId;
        errorArr.unshift(obj);
      } else {
        obj.errorWords = temArr[i];
        obj.voiceSystemId = that.data.errorWordsObj.voiceSystemId;
        errorArr.push(obj);
      }

    }
    errorObj.errWords = errorArr;
    wx.navigateTo({
      url: '../errorWords/errorWords?errorwords=' + JSON.stringify(errorObj)
    })
  },

  // 和同学一起练（生成擂台主信息）
  togetherClassmate: function () {
    var that = this;
    commonAPI.arenaInvitationCard({
      voiceResultId: that.data.scoreDetail.voiceResultId,
      pageUrl: util.getCurrentPageUrl()
    }).then(res => {
      if (res.code == '200') {
        wx.navigateTo({
          url: '../arena/arena?scene=' + res.data.myVoiceInfo.arenaId
        });
      } else {
        FN.Toast(res.message)
      }
    })
  },

  // 刷新积分
  refreshItegral: function () {
    app.setPageTabBarBadge();//实时更新主菜单我的消息数字
    setTimeout(() => {
      this.setData({
        integralNum: app.globalData.userInfo.integralObj == null ? 0 : app.globalData.userInfo.integralObj.integralNum
      })
    }, 1000);
  },

  // 1对1纠音 先查看本句是否已经有预约，有预约，且老师已经回复，就直接跳转到老师纠音回复页
  getTeacherList: function () {
    var that = this;
    commonAPI.getTeacherRanking({}).then(res => {
      if (res.code == '200') {
        that.setData({
          teacherList: res.data
        })
        console.log(that.data.teacherList)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError((res) => {
      // 播放音频失败的回调
      that.setData({
        btns: '1',
      })
    })
    this.innerAudioContext.src = this.data.scoreDetail.tempFilePath;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.refreshItegral();// 是否为会员
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {

  }
})